<template>
	<div class="col-md-8 topic-bg">
		<div class="well fade in daytips" v-if="query || key">
			<div v-if="key">关于 <font color="red">"{{key}}"</font> 的搜索结果如下
				<span style="float:right">共 <font color="red">"{{list.length}}"</font> 条数据</span>
			</div>
			<span v-else>{{query}}</span>
		</div>
		<item :list="list"></item>
		<pagination :total="total" :page="page" @pageSelect="pageSelect"></pagination>
	</div>
</template>

<script>
	import Item from 'particals/item/item'
	import Pagination from 'packages/pagination/pagination'
	import {scrollTop} from 'common/func'
    import {mapGetters, mapMutations} from 'vuex'
    import {setTitle} from 'common/dom'
    import eventVue from 'common/event'

	export default {
		computed: {
			query() {
				return this.userSay
			},
            ...mapGetters([
              'userSay'
            ])
        },
		data() {
			return {
				list: [],
				page: 1,
				page_size: 6,
				total: 0,
				cate_id: '',
				tag_id: '',
				key: ''
			}
		},
		created() {
            setTitle(this.$title.topic)
			this.__getList()
		},
		methods: {
			pageSelect(page) {
            	this.page = page;
				this.$router.push(this.__buildRouter())
			},
			routerChange() {
				this.__getList()
			},
			__getQuery() {
				this.cate_id = parseInt(this.$route.query.cate_id) || ''
				this.tag_id = parseInt(this.$route.query.tag_id) || ''
				this.page = parseInt(this.$route.query.page) || 1
				this.key = this.$route.query.key || ''
			},
			__getList() {
				this.__getQuery()
				this.$http.get('topics',{params: this.__buildParams()}).then((resource)=>{
					let total = resource.data.meta.total_nums
					this.total = Math.ceil(total / this.page_size)
					this.list = resource.data.data
					this.setDataReady(true)
					scrollTop()
				});
			},
			__buildParams() {
				let params = {
					page: this.page,
					page_size: this.page_size,
				}
				if(this.cate_id != '') {
					params.cate_id = this.cate_id
				}
				if(this.tag_id != '') {
					params.tag_id = this.tag_id
				}
				if(this.key != '') {
					params.key = this.key
				}
				let _this = this
				setTimeout(()=> {
					eventVue.$emit('keyChange', _this.key)
				}, 80)
				return params
			},
			__buildRouter() {
				let query = this.__buildParams()
				delete query.page_size
				return {
					path:'/topics',
					query: query
            	}
			},
            ...mapMutations({
              setDataReady: 'SET_DATA_READY'
            })
		},
		components: {
			Item,Pagination
		},
		watch: {
			'$route': 'routerChange'
		}
	}
</script>

<style lang="scss" scope>
	.topic-bg {
		.well {
			min-height: 20px;
		    border-radius: 4px;
		    -webkit-box-shadow: 0 0 5px #c2c2c2;
		    -moz-box-shadow: 0 0 5px #c2c2c2;
		    box-shadow: 0 0 5px #c2c2c2;
		}
		.daytips{
			padding:15px;
			background-color: #fff;
			box-shadow: none;
			span{
				line-height:20px;
			}
		}
	}
</style>